package com.example.crossborderecommerce.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.crossborderecommerce.entity.*;
import com.example.crossborderecommerce.mapper.CustomerOrderMapper;
import com.example.crossborderecommerce.mapper.FinanceReceiptMapper;
import com.example.crossborderecommerce.service.IAdminService;
import com.example.crossborderecommerce.service.IFinanceReceiptService;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 财务单据模块
 *
 * @author Yolanda
 * @since 2024-05-09
 */
@RestController
@Transactional
@RequestMapping("/finance-receipt")
public class FinanceReceiptController {
    @Resource
    IFinanceReceiptService financeReceiptService;
    @Resource
    IAdminService adminService;
    @Resource
    FinanceReceiptMapper financeReceiptMapper;
    @Resource
    CustomerOrderMapper customerOrderMapper;

    /**
     * 添加财务单据
     * @param financeReceipt
     * @return
     */
    @PostMapping("/save")
    public Result save(@RequestBody FinanceReceipt financeReceipt){
        boolean res = financeReceiptService.save(financeReceipt);
        if(res){
            return Result.success("添加财务单据成功！");
        }
        return Result.error("添加财务单据失败！");
    }
    /**
     * 删除某个单据
     * @param financeReceipt
     * @return
     */
    @PostMapping("/delete")
    public Result delete(@RequestBody FinanceReceipt financeReceipt){
        boolean res = financeReceiptService.removeById(financeReceipt);
        if(res){
            return Result.success("删除财务款单成功！");
        }
        return Result.error("删除财务款单失败！");
    }


    /**
     * 删除一系列财务单据
     * @param ids
     * @return
     */
    @GetMapping("/deleteBatch")
    public Result deleteBatch(@RequestParam String ids) {
        List<String> financeReceiptIds = Arrays.stream(ids.split(",")).collect(Collectors.toList());
        boolean res = financeReceiptService.removeByIds(financeReceiptIds);
        if(res) {
            return Result.success("删除财务单据成功！");
        }
        return Result.error("删除财务单据失败！");
    }

    /**
     * 修改财务单据
     * @param financeReceipt
     * @return
     */
    @PostMapping("/update")
    public Result update(@RequestBody FinanceReceipt financeReceipt) {
        boolean res = financeReceiptService.saveOrUpdate(financeReceipt);
        if (res) {
            return Result.success("修改财务单据成功！");
        }
        return Result.error("修改财务单据失败！");
    }

    /**
     * 分页查询所有财务单据
     * @param adminId
     * @param type
     * @param orderId
     * @param orderType
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/findPage")
    public Result findPage(@RequestParam(defaultValue = "-1") String adminId,
                           @RequestParam(defaultValue = "") String type,
                           @RequestParam(defaultValue = "") String orderId,
                           @RequestParam(defaultValue = "") String orderType,
                           @RequestParam Integer pageNum,
                           @RequestParam Integer pageSize) {
        QueryWrapper<FinanceReceipt> queryWrapper = new QueryWrapper<>();
        if(!adminId.equals("-1")) {
            queryWrapper.eq("admin_id", adminId);
        }
        if(!type.isEmpty()) {
            queryWrapper.eq("type", type);
        }
        if(!orderType.equals("全部") && !orderType.isEmpty()) {
            queryWrapper.eq("order_type", orderType);
        }
        queryWrapper.like("order_id", orderId);
        Page<FinanceReceipt> financeReceiptPage = financeReceiptService.page(new Page<>(pageNum, pageSize), queryWrapper);
        for(FinanceReceipt financeReceipt : financeReceiptPage.getRecords()) {
            Admin admin = adminService.getById(financeReceipt.getAdminId());
            financeReceipt.setAdminName(admin.getName());
        }
        return Result.success("成功查询所有财务单据信息！",financeReceiptPage);
    }
    /**
     * 导出款单
     * @param adminId
     * @param type
     * @param orderId
     * @param orderType
     * @param response
     * @return
     */
    @GetMapping("exportFinanceReceiptList")
    public Result exportFinanceReceiptList(@RequestParam(defaultValue = "-1") String adminId,
                                         @RequestParam(defaultValue = "") String type,
                                         @RequestParam(defaultValue = "") String orderId,
                                         @RequestParam(defaultValue = "") String orderType,
                                         HttpServletResponse response) {
        QueryWrapper<FinanceReceipt> queryWrapper = new QueryWrapper<>();
        if(!adminId.equals("-1")) {
            queryWrapper.eq("admin_id", adminId);
        }
        if(!type.isEmpty()) {
            queryWrapper.eq("type", type);
        }
        if(!orderType.equals("全部") && !orderType.isEmpty()) {
            queryWrapper.eq("order_type", orderType);
        }
        queryWrapper.like("order_id", orderId);
        List<FinanceReceipt> financeReceiptList = financeReceiptService.list(queryWrapper);
        for(FinanceReceipt financeReceipt : financeReceiptList) {
            Admin admin = adminService.getById(financeReceipt.getAdminId());
            financeReceipt.setAdminName(admin.getName());
        }
        HSSFWorkbook wb = new HSSFWorkbook(); // 导出到excel文件中
        HSSFSheet sheet = wb.createSheet("表一");
        HSSFRow row = sheet.createRow(0);
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        HSSFCell cell = row.createCell((short) 0);
        cell.setCellValue("单据编号");
        cell.setCellStyle(style);
        cell = row.createCell((short) 1);
        cell.setCellValue("订单编号");
        cell.setCellStyle(style);
        cell = row.createCell((short) 2);
        cell.setCellValue("订单类型");
        cell.setCellStyle(style);
        cell = row.createCell((short) 3);
        cell.setCellValue("金额");
        cell.setCellStyle(style);
        cell = row.createCell((short)4);
        cell.setCellValue("负责人");
        cell.setCellStyle(style);
        cell = row.createCell((short)5);
        cell.setCellValue("创建时间");
        cell.setCellStyle(style);
        cell = row.createCell((short)6);
        cell.setCellValue("完成时间");
        cell.setCellStyle(style);
        SimpleDateFormat inputDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        SimpleDateFormat outputDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i = 0; i < financeReceiptList.size(); i++) {
            row = sheet.createRow(i + 1);
            FinanceReceipt financeReceipt = financeReceiptList.get(i);
            row.createCell((short) 0).setCellValue(financeReceipt.getId());
            row.createCell((short) 1).setCellValue(financeReceipt.getOrderId());
            row.createCell((short) 2).setCellValue(financeReceipt.getOrderType());
            row.createCell((short) 3).setCellValue(financeReceipt.getPrice());
            row.createCell((short) 4).setCellValue(financeReceipt.getAdminName());
            try {
                Date endTine=inputDateFormat.parse(financeReceipt.getEndTime().toString());
                Date createTime = inputDateFormat.parse(financeReceipt.getCreateTime().toString()); // 假设 getCreateTime 返回的是 String
                row.createCell((short) 5).setCellValue(outputDateFormat.format(createTime));
                row.createCell((short)6).setCellValue(outputDateFormat.format(endTine));
            } catch (ParseException e) {
                row.createCell((short) 5).setCellValue(financeReceipt.getCreateTime().toString());
                row.createCell((short)6).setCellValue(financeReceipt.getEndTime().toString());
            }
        }
        String fileName = "exportFinanceReceiptList.xls";
        // 用户下载
        try {
            ServletOutputStream outputStream = null;
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, "UTF-8"));
            outputStream = response.getOutputStream();
            wb.write(outputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Result.success("exportFinanceReceiptList");
    }

    /**
     * 获取成本价（包括物流成本和产品成本）
     * @return
     */
    @GetMapping("/getTotalCost")
    public Result getTotalCost() {
        return Result.success(financeReceiptMapper.getTotalCost());
    }

    /**
     * 获取近七天成本价（包括物流成本和产品成本）
     * @return
     */
    @GetMapping("/getTotalCostInWeek")
    public Result getTotalCostInWeek() {
        LocalDate today = LocalDate.now();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<Double> totalCostInWeek = new LinkedList<>();
        // 循环七天
        for (int i = 6; i >= 0; --i) {
            // 今天的日期
            LocalDate currentDay = today.plusDays(-i);
            // 构建今天的开始时间（0时0分0秒）
            LocalDateTime startOfDay = LocalDateTime.of(currentDay, LocalTime.MIDNIGHT);
            // 构建今天的结束时间（接近午夜的一秒前，这里简化为23:59:59）
            LocalDateTime endOfDay = LocalDateTime.of(currentDay, LocalTime.of(23, 59, 59));
            // 将LocalDateTime转换为Date
            Date startDate = Date.from(startOfDay.atZone(ZoneId.systemDefault()).toInstant());
            Date endDate = Date.from(endOfDay.atZone(ZoneId.systemDefault()).toInstant());
            // 格式化日期并打印
            String formattedStartDate = sdf.format(startDate);
            String formattedEndDate = sdf.format(endDate);
            double cost = financeReceiptMapper.getTotalCostDuration(formattedStartDate, formattedEndDate);
            totalCostInWeek.add(cost);
        }
        return Result.success(totalCostInWeek);
    }

    /**
     * 获取昨天成本价（包括物流成本和产品成本）
     * @return
     */
    @GetMapping("/getTotalCostInYesterday")
    public Result getTotalCostInYesterday() {
        LocalDate today = LocalDate.now();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        LocalDate currentDay = today.plusDays(-1);
        LocalDateTime startOfDay = LocalDateTime.of(currentDay, LocalTime.MIDNIGHT);
        LocalDateTime endOfDay = LocalDateTime.of(currentDay, LocalTime.of(23, 59, 59));
        Date startDate = Date.from(startOfDay.atZone(ZoneId.systemDefault()).toInstant());
        Date endDate = Date.from(endOfDay.atZone(ZoneId.systemDefault()).toInstant());
        String formattedStartDate = sdf.format(startDate);
        String formattedEndDate = sdf.format(endDate);
        double cost = financeReceiptMapper.getTotalCostDuration(formattedStartDate, formattedEndDate);
        return Result.success(cost);
    }

    /**
     * 根据orderType获得对应price
     * @return
     */
    @GetMapping("/getPriceByOrderType")
    public Result getPriceByOrderType(@RequestParam(defaultValue = "") String orderType) {
        return Result.success(financeReceiptMapper.getPriceByOrderType(orderType));
    }

    /**
     * 根据type获得对应price
     * @return
     */
    @GetMapping("/getPriceByType")
    public Result getPriceByType(String type) {
        return Result.success(financeReceiptMapper.getPriceByType(type));
    }
}
